package cn.tmpan.project.filter;

import cn.tmpan.project.filter.wrapper.RequestWrapper;
import cn.tmpan.project.utils.PropertiesUtil;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author tieMinPan
 * @Desc: @Order中的value越小，优先级越高。
 * @date 2019-09-19 15:35
 */
@Component
@WebFilter(filterName = "crownFilter", urlPatterns = "/*")
@Order(value = 1)
public class CrownFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        // 获取路径地址
        String path = req.getRequestURI().substring(req.getContextPath().length()).replaceAll("[/]+$", "");
        String[] array = new String[]{};
        String excludeUrl = PropertiesUtil.getProperty("crownFilter_excludeUrl");
        if (!StringUtils.isEmpty(excludeUrl)) {
            array = excludeUrl.split(",");
        }
        boolean allowedPath = false;
        for (String s : array) {
            if (path.indexOf(s) > -1) {
                allowedPath = true;
                break;
            }
        }
        if (allowedPath) {
            filterChain.doFilter(req, servletResponse);
        } else {
            filterChain.doFilter(new RequestWrapper(req), servletResponse);
        }

    }

    @Override
    public void destroy() {

    }
}
